package member

import (
	"context"
	"errors"
	"group-buy/group_buy/internal/models"
	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveBusinessMemberLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveBusinessMemberLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveBusinessMemberLogic {
	return &SaveBusinessMemberLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveBusinessMemberLogic) SaveBusinessMember(req *types.BusinessMember) (resp *types.BusinessMember, err error) {
	user := &models.Member{Id: req.MemberId}
	get, err := l.svcCtx.Engine.Get(user)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("查询用户失败")
	}
	//if len(user.LsUser) <= 0 {
	//	return nil, errors.New("请先完成实名认证")
	//}
	//if len(user.LsCard) <= 0 {
	//	return nil, errors.New("请先完成银行卡绑定")
	//}
	business := &models.Business{Id: req.BusinessId}
	get, err = l.svcCtx.Engine.Get(business)
	if err != nil {
		return nil, err
	}

	exist, err := l.svcCtx.Engine.Exist(&models.BusinessMember{MemberId: req.MemberId, BusinessId: req.BusinessId})
	if err != nil {
		return nil, err
	}
	if exist {
		return req, nil
	}

	if !get {
		return nil, errors.New("获取商家失败，请稍后重试")
	}
	m := &models.BusinessMember{
		Id:           req.Id,
		MemberId:     req.MemberId,
		MemberName:   user.Name,
		BusinessId:   req.BusinessId,
		InviteId:     req.InviteId,
		BusinessName: business.Name,
		MemberPhone:  user.Phone,
	}
	if m.Id > 0 {
		_, err = l.svcCtx.Engine.ID(m.Id).Update(m)
		if err != nil {
			return nil, err
		}
	} else {
		_, err = l.svcCtx.Engine.Insert(m)
		if err != nil {
			return nil, err
		}
	}
	req.Id = m.Id
	return req, nil
}
